package framework.web;

import framework.service.impl.UserServiceImp;
import framework.pojo.User;
import framework.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class RegisterServlet extends HttpServlet {

    private UserService userService = new UserServiceImp();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String repassword = req.getParameter("repassword");
        String email = req.getParameter("email");

        if (username.equals("") || password.equals("") || repassword.equals("") || email.equals("")) {
            req.setAttribute("alertMsg", "信息输入不完整！");
            req.getRequestDispatcher("/page/user/register.jsp").forward(req, resp);
        } else {
//            System.out.println(username+"\n"+password+"\n"+email+"\n");
//            System.out.println(username.equals("")+"\n"+password.equals("")+"\n"+email.equals(""));
            User user = new User(null, username, password, email);

            //首先检查用户名是否可用
            if (userService.existsUsername(username)) {

                req.setAttribute("alertMsg", "用户名已存在！");
                req.getRequestDispatcher("/page/user/register.jsp").forward(req, resp);

            } else {
                if (password.equals(repassword)) {
                    userService.registUser(user);
                    req.getRequestDispatcher("/page/user/registerSuccess.jsp").forward(req, resp);

                } else {
                    req.setAttribute("alertMsg", "两次输入的密码不同！");
                    req.getRequestDispatcher("/page/user/register.jsp").forward(req, resp);
                }
            }
        }
    }
}
